<script setup lang='ts'>
  import { nextTick, reactive, ref } from 'vue';
  import { guild_roomApi } from '@/api/controller';
  import { ToastSuccess, ToastWarning, Toastloading } from '@/utils/public';
  import serachUserid from '@/components/serachUserid/index.vue';
  const formLabelWidth = '160px'
  const dataForm = ref(),
  serachUseridRef = ref();
  const $emit = defineEmits(['updateList'])
  const action = reactive({
    dialogFormVisible:false,
    disabled:false,
  })
  interface formQuert {
    room_id:number
    user_id:number
  }
  let form = reactive({} as formQuert)
  const formRules = {
    user_id: [{ required: true, message: "请输入用户UUID", trigger: "blur" }],
  }
  const handleSubmit = ()=>{
    dataForm.value.validate(async(valid:any)=>{
      if(!valid) return
      const loading = Toastloading()
      await guild_roomApi.setRoomFinanceUser(form).then(()=>{
        loading.close()
        ToastSuccess('设置指定分成用户成功')
        $emit('updateList')
        closeDialog()
      }).catch(()=>{
        loading.close()
      })
    })
  }
  const getUserInfo = async()=>{
    const loading = Toastloading()
    const res = await guild_roomApi.getRoomFinanceUser({
      room_id:form.room_id
    })
    loading.close()
    const { user_id='', uuid='' } = res?.data || { user_id:'', uuid:''}
    form.user_id = user_id
    return uuid
  }
  const openDialog = async(query:any = {})=> {
    const { room_id } = query
    if(!room_id) return ToastWarning('缺少房间ID')
    form.room_id = room_id
    const uuid = await getUserInfo()
    action.dialogFormVisible = true
    nextTick(()=>{
      if(uuid) serachUseridRef?.value.remoteMethod(uuid)
    })
  }
  const closeDialog = ()=>{
    form = reactive({} as formQuert)
    nextTick(() => {
      dataForm.value.clearValidate();
    });
    action.dialogFormVisible = false
  }
  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
      top="10vh"
      class="xm-dialog input-width"
      v-model="action.dialogFormVisible"
      :close-on-click-modal="action.disabled"
      :show-close="action.disabled"
      :close-on-press-escape="action.disabled"
      width="40%"
      title="指定分成用户ID">
      <el-form ref="dataForm" :model="form" :rules="formRules">
        <el-form-item :label-width="formLabelWidth" label="用户UUID">
          <serachUserid ref="serachUseridRef" v-model:user_id="form.user_id"/>
        </el-form-item>
      </el-form>
      <template v-if="!action.disabled" #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>